#!/usr/bin/env python
# -*- coding: utf-8 -*-

__version__ = "0.2.1"


from grdlog.sqlpipe import SQLFactory, SQLPipe
from twisted.application import internet, service

from ConfigParser import ConfigParser, NoSectionError, NoOptionError

class ImproperlyConfigured(Exception):
    pass

conf = ConfigParser()
conf.read('/etc/grdlog.conf')
conf._defaults['host'] = 'localhost'

dsn = {'db': 'name', 'host': 'host', 'user': 'user', 'passwd': 'password'}
for key in dsn.keys():
    try:
        opt = dsn[key]
        dsn[key] = conf.get('database', opt)
    except NoSectionError:
        raise ImproperlyConfigured, "Bad configuration - no 'database' section"
    except NoOptionError:
        raise ImproperlyConfigured, "Bad configuration - no %r option" % opt

try:
    factory = SQLFactory('MySQLdb', **dsn)
except: # this is not much useful, cause a connection is the main problem here
    exit
else:
    application = service.Application('sqlpipe', uid=1, gid=1)
    
    # TCPServer has a factory as second arg,
    # but UDPServer wants a protocol!
    
    internet.UDPServer(514, SQLPipe(factory)).setServiceParent(
        service.IServiceCollection(application))
